<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\library\helper;
use app\common\exception\BaseException;
use app\common\service\bangdou\Common as CommonService;


/**
 * 三券支付订单回调
 * Class PayNotice
 * @package app\api\controller
 */
class PayNotice extends Controller
{
    // 订单模型
    private $modelClass = [
        OrderTypeEnum::ORDER => \app\api\service\order\PaySuccess::class,
        OrderTypeEnum::RECHARGE => \app\api\service\recharge\PaySuccess::class,
    ];
    /**
     * 支付成功异步通知
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function bangnuoNotice()
    {
        $data =$this->request->param();
        $log_file = runtime_root_path() .'api/log/bd_wx_pay_'.date('y-m-d').'.log';
        file_put_contents($log_file, print_r($data, true)."\n", FILE_APPEND);
        $message = CommonService::checkSign($data);
        if(isset($message['code']) && $message['code']==2){
            return $this->renderError($message['message'] ?: '订单回调失败');
        }

        $attach = helper::jsonEncode(['order_type' => OrderTypeEnum::ORDER]);//商城订单
        // 实例化订单模型
        $model = $this->getOrderModel($data['out_trade_no'], $attach);
        // 订单信息
        $order = $model->getOrderInfo();
        empty($order) && $this->renderError('订单不存在');

        // 订单支付成功业务处理
        $status = $model->onPaySuccess(OrderPayTypeEnum::WECHAT, $data);
        if ($status == false) {
            return $this->returnCode(false, '数据更新失败');
        }
        // 返回状态
        return $this->renderSuccess([
            'code'=>1,
            'msg' => '回调成功',   // 订单id
        ]);
    }

    /**
     * 实例化订单模型 (根据attach判断)
     * @param $orderNo
     * @param null $attach
     * @return mixed
     */
    private function getOrderModel($orderNo, $attach = null)
    {
        $attach = helper::jsonDecode($attach);
        // 判断订单类型返回对应的订单模型
        $model = $this->modelClass[$attach['order_type']];
        return new $model($orderNo);
    }
}